﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Redmine.Laptop.Common.Constants;
using Redmine.Laptop.Common.Core;
using Redmine.Laptop.Reports;

namespace Redmine.Laptop.Console
{
    class Program
    {
        private static Dictionary<string, object> PrepareArguments(IEnumerable<string> args)
        {
            const string keyPattern = @":(\S+)=";
            const string valuePattern = @"=(\S+)";

            var arguments =
               args.ToDictionary
               (
                   a => Regex.Matches(a, keyPattern)[0].Value.ToLower().Trim(':', '='),
                   a => (object)Regex.Matches(a, valuePattern)[0].Value.Trim('=')
               );

            if (!arguments.ContainsKey(Constant.ArgKeys.From))
                arguments.Add(Constant.ArgKeys.From, DateTime.Now.AddDays(-6));
            if (!arguments.ContainsKey(Constant.ArgKeys.To))
                arguments.Add(Constant.ArgKeys.To, DateTime.Now);
            if (!arguments.ContainsKey(Constant.ArgKeys.Report))
                arguments.Add(Constant.ArgKeys.Report, ReportType.Timesheet.ToString());
            if(!arguments.ContainsKey(Constant.ArgKeys.SavePath))
                arguments.Add(Constant.ArgKeys.SavePath, string.Empty);
            return arguments;
        }

        private static void SaveReport(FileStorage file, string fileName, string savePath)
        {
            if (!string.IsNullOrEmpty(savePath))
                file.CopyTo(Path.Combine(savePath, fileName + ".xlsx"));
            else
            {
                var dialog = new SaveFileDialog
                                 {
                                     DefaultExt = ".xlsx",
                                     DereferenceLinks = true,
                                     ValidateNames = true,
                                     FileName = fileName,
                                     Filter = @"Excel Book|*.xlsx| All Files|*.*"
                                 };
                var result = dialog.ShowDialog();
                if (result == DialogResult.OK)
                    file.CopyTo(dialog.FileName);
            }
            file.Delete();
        }

        [STAThread]
        static void Main(string[] args)
        {
            var arguments = PrepareArguments(args);
            var reportDirector = new ReportDirector();
            var report = reportDirector.Construct(arguments);
            var file = report.Build();
            SaveReport(file, report.ReportName, arguments[Constant.ArgKeys.SavePath].ToString());
            report.Dispose();
        }
    }
}
